<template>
  <div class="address-book-container">
    <el-card class="address-card">
      <template #header>
        <div class="card-header">
          <h2>地址簿</h2>
          <div class="header-actions">
            <!-- 寄件/收件按钮移动到新增地址前面 -->
            <div class="address-tabs">
              <el-radio-group v-model="addressType" size="default" @change="handleAddressTypeChange">
                <el-radio-button label="send">寄件地址</el-radio-button>
                <el-radio-button label="receive">收件地址</el-radio-button>
              </el-radio-group>
            </div>
            <el-button type="primary" @click="goToAddAddress">
              <el-icon><Plus /></el-icon>新增地址
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 地址列表 -->
      <div class="address-list" v-if="addressList.length > 0">
        <el-table :data="addressList" style="width: 100%" stripe>
          <el-table-column prop="contactName" label="联系人" width="120" />
          <el-table-column prop="contactPhone" label="电话" width="150" />
          <el-table-column prop="fullAddress" label="地址" min-width="200" show-overflow-tooltip />
          <el-table-column prop="updatedAt" label="更新时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.updatedAt) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="editAddress(row)">
                修改
              </el-button>
              <el-button type="danger" size="small" @click="deleteAddress(row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        
        <!-- 分页组件 -->
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
      
      <!-- 空状态 -->
      <div class="empty-placeholder" v-else>
        <el-empty description="暂无地址数据"></el-empty>
      </div>
    </el-card>
    
    <!-- 编辑地址对话框 -->
    <el-dialog v-model="editDialogVisible" title="修改地址" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="联系人" prop="contactName">
          <el-input v-model="editForm.contactName" placeholder="请输入联系人姓名" />
        </el-form-item>
        <el-form-item label="电话" prop="contactPhone">
          <el-input v-model="editForm.contactPhone" placeholder="请输入联系人电话" />
        </el-form-item>
        <el-form-item label="地址" prop="fullAddress">
          <el-input 
            v-model="editForm.fullAddress" 
            type="textarea" 
            :rows="3"
            placeholder="请输入详细地址" 
          />
        </el-form-item>
        <el-form-item label="地址类型" prop="isDefault">
          <el-radio-group v-model="editForm.isDefault">
            <el-radio :label="1">寄件地址</el-radio>
            <el-radio :label="0">收件地址</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import { userApi, type Address, type AddressListResponse } from '@/api/user'

const router = useRouter()
const addressType = ref('send') // 'send' 或 'receive'
const addressList = ref<Address[]>([])
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)
const loading = ref(false)

// 编辑对话框相关
const editDialogVisible = ref(false)
const editFormRef = ref<FormInstance>()
const editForm = reactive<Address>({
  addressId: undefined,
  contactName: '',
  contactPhone: '',
  fullAddress: '',
  isDefault: 1
})

const editRules = {
  contactName: [
    { required: true, message: '请输入联系人姓名', trigger: 'blur' }
  ],
  contactPhone: [
    { required: true, message: '请输入联系人电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  fullAddress: [
    { required: true, message: '请输入详细地址', trigger: 'blur' }
  ]
}

// 跳转到新增地址页面
const goToAddAddress = () => {
  router.push('/addressbook/add')
}

// 获取地址列表
const getAddressList = async () => {
  try {
    loading.value = true
    let response
    
    if (addressType.value === 'send') {
      response = await userApi.queryAllSendAddress(currentPage.value, pageSize.value)
    } else {
      response = await userApi.queryAllReceiveAddress(currentPage.value, pageSize.value)
    }
    
    console.log('API响应:', response)
    
    if (response.code === 200) {
      // 数据在 response.msg 字段中
      const data = response.msg
      addressList.value = data.list || []
      total.value = data.total || 0
      
      console.log('解析后的地址列表:', addressList.value)
      console.log('总数:', total.value)
    } else {
      ElMessage.error(response.message || response.data || '获取地址列表失败')
    }
  } catch (error: any) {
    console.error('获取地址列表失败:', error)
    ElMessage.error(error.message || '获取地址列表失败')
  } finally {
    loading.value = false
  }
}

// 地址类型切换
const handleAddressTypeChange = () => {
  currentPage.value = 1
  getAddressList()
}

// 分页大小改变
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize
  currentPage.value = 1
  getAddressList()
}

// 当前页改变
const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage
  getAddressList()
}

// 编辑地址
const editAddress = (address: Address) => {
  Object.assign(editForm, address)
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  if (!editFormRef.value) return
  
  try {
    await editFormRef.value.validate()
    
    const response = await userApi.updateAddress(editForm)
    
    if (response.code === 200) {
      ElMessage.success('修改地址成功')
      editDialogVisible.value = false
      getAddressList() // 刷新列表
    } else {
      ElMessage.error(response.message || '修改地址失败')
    }
  } catch (error: any) {
    console.error('修改地址失败:', error)
    ElMessage.error(error.message || '修改地址失败')
  }
}

// 删除地址
const deleteAddress = async (address: Address) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除联系人"${address.contactName}"的地址吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await userApi.deleteAddress(address.addressId!)
    
    if (response.code === 200) {
      ElMessage.success('删除地址成功')
      getAddressList() // 刷新列表
    } else {
      ElMessage.error(response.message || '删除地址失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('删除地址失败:', error)
      ElMessage.error(error.message || '删除地址失败')
    }
  }
}

// 页面加载时获取数据
onMounted(() => {
  getAddressList()
})

// 格式化日期时间
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '-'
  
  const date = new Date(dateTimeStr)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}
</script>

<style scoped>
.address-book-container {
  padding: 20px;
}

.address-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 16px;
}

.address-tabs {
  margin: 0;
}

.address-list {
  margin-top: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.empty-placeholder {
  margin: 60px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>